package com.rongshu.sendmessage.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.adapter.MessageAdapter;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.bean.HealthyRegimenList;
import com.rongshu.sendmessage.util.AnimationUtil;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.ObjectUtil;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.httpUtil.Constant;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.util.itemDecoration.MyItemDecoration;
import com.rongshu.sendmessage.view.refresh.ProgressLayout;
import com.rongshu.sendmessage.view.refresh.RefreshListenerAdapter;
import com.rongshu.sendmessage.view.refresh.TwinklingRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchActivity extends BaseActivity {

    private ImageView iv_search;
    private EditText et_search;
    private String keyword;
    private TextView title;
    private LinearLayout ll_list;
    private RecyclerView recycleView;
    private MessageAdapter mAdapter;
    private ArrayList<HealthyRegimenList> mList;
    private int page;
    private String pullType;
    private TwinklingRefreshLayout list_refresh;
    private View noresult_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        mContext=this;
        initView();
        page=1;
        pullType = Constant.PULLTYPE_DOWN;
        initData();

    }

    private void initData() {
        DialogUtil.showProgress(mContext);
        Map<String, String> param = new HashMap<String, String>();
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        param.put("keyword", keyword);
        param.put("page", page+"");
        OkGo.<String>post(new HYContent().SEARCH_FABU_LIST_URL).params(param).tag("SEARCH_FABU_LIST_URL").
                execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtil.hideProgress();
                        if (pullType.equals(Constant.PULLTYPE_DOWN)) {
                            list_refresh.finishRefreshing();
                            mList.clear();
                        } else {
                            list_refresh.finishLoadmore();
                        }
                        try {
                            IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
                            final int code = jr.getCode();
                            if (code>0){
                                List<HealthyRegimenList> messageLists = JSON.parseArray(JSON.toJSONString(jr.getJSONArrayData()), HealthyRegimenList.class);
                                if (messageLists.size()==0&&pullType.equals(Constant.PULLTYPE_UP)) {
                                    ToastUtils.show(mContext,getResources().getString(R.string.no_more));
                                    return;
                                }
                                mList.addAll(messageLists);
                                mAdapter.setmList(mList);
                                mAdapter.notifyDataSetChanged();
                                if (mList.size()==0){
                                    recycleView.setVisibility(View.GONE);
                                    noresult_view.setVisibility(View.VISIBLE);
                                }else{
                                    noresult_view.setVisibility(View.GONE);
                                    recycleView.setVisibility(View.VISIBLE);
                                }
                            }else{
                                ToastUtils.show(mContext,jr.getMsg());
                                recycleView.setVisibility(View.GONE);
                                noresult_view.setVisibility(View.VISIBLE);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            recycleView.setVisibility(View.GONE);
                            noresult_view.setVisibility(View.VISIBLE);
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        DialogUtil.hideProgress();
                        ll_list.setVisibility(View.GONE);
                        noresult_view.setVisibility(View.GONE);

                        if (pullType.equals(Constant.PULLTYPE_DOWN)) {
                            list_refresh.finishRefreshing();
                        } else {
                            list_refresh.finishLoadmore();
                        }
                    }
                });
    }

    private void initView() {
        mList=new ArrayList<>();
        View titleLayLeft = findViewById(R.id.titleLayLeft);
        TextView tv_no_text = findViewById(R.id.tv_no_text);
        tv_no_text.setText("这里空空如也");
        noresult_view=findViewById(R.id.noresult_view);
        ll_list=findViewById(R.id.ll_list);

        titleLayLeft.setOnClickListener(view->finish());
        title=findViewById(R.id.title);
        title.setText("搜索");
        initRecycle();
        list_refresh = findViewById(R.id.list_refresh);
        ProgressLayout headerView = new ProgressLayout(mContext);
        list_refresh.setHeaderView(headerView);
        list_refresh.setOverScrollRefreshShow(false);
        list_refresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                pullType = Constant.PULLTYPE_DOWN;
                page = 1;
                initData();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                pullType = Constant.PULLTYPE_UP;
                page++;
                initData();
            }
        });
        et_search=findViewById(R.id.et_search);
        iv_search=findViewById(R.id.iv_search);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void afterTextChanged(Editable editable) {
                if (editable!=null&& !ObjectUtil.isBlank(editable.toString()))
                    keyword=editable.toString();
                else {
                    keyword="";
                }
            }
        });
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    page=1;
                    pullType = Constant.PULLTYPE_DOWN;
                    initData();


                    return true;
                }

                return false;
            }
        });
    }

    private void initRecycle() {

        recycleView = findViewById(R.id.recycleView);
        recycleView.setLayoutAnimation(AnimationUtil.getAnimationController());
        recycleView.setHasFixedSize(true);//设置固定大小
        recycleView.setItemAnimator(new DefaultItemAnimator());//设置默认动画
        recycleView.addItemDecoration(new MyItemDecoration());
        recycleView.addItemDecoration(new MyItemDecoration(0, 0));
        GridLayoutManager mLayoutManage = new GridLayoutManager(mContext, 1);
        recycleView.setLayoutManager(mLayoutManage);
        mAdapter = new MessageAdapter(mContext,"more", R.layout.message_item, mList);
        recycleView.setAdapter(mAdapter);
        //recycleview的点击事件
        mAdapter.setOnItemClickListener((view, position) -> {
            if (view.getId()==R.id.ll_bianji){
                //去编辑

            }else{
                Intent intent=new Intent(mContext, MessageDetailActivity.class);
                String id = mList.get(position).getId();
                intent.putExtra("articleId",id);
                startActivity(intent);
            }
        });
    }


    public void onClick(View view) {
        if (view.getId()==R.id.iv_search){
            page=1;
            pullType = Constant.PULLTYPE_DOWN;
            initData();
        }
    }
}